"use client"
import React, { useState, useEffect } from 'react';
import { ArrowUp, ArrowDown, ChevronLeft, ChevronRight } from 'lucide-react';
import { supabase } from '@/controller/supabase';
import { useTranslations } from 'next-intl';
import { getUser } from '@/controller/auth';
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import { Skeleton } from '@/components/ui/skeleton';
import Link from 'next/link';
import { get } from '@/lib/request';
import CreditsPurchase from '@/components/billing/credits-purchase';
import { User } from '@supabase/supabase-js';
interface Transaction {
  id: string;
  amount: number;
  type: string;
  status: string;
  created_at: string;
}

interface WalletBalance {
  balance: number;
  frozen: number;
}

export default function BillingPage() {
  // const user = getUser();
  const t = useTranslations('billing');
  const [wallet, setWallet] = useState<WalletBalance | null>(null);
  const [transactions, setTransactions] = useState<Transaction[]>([]);
  const [loading, setLoading] = useState(true);
  const [currentPage, setCurrentPage] = useState(1);
  const [totalPages, setTotalPages] = useState(1);
  const [transactionType, setTransactionType] = useState<'recharge' | 'final_deduct'>('recharge');
  const pageSize = 10;
  const [user, setUser] = useState<User | null>(null);
  useEffect(() => {
    const getUserInfo = async () => {
      try {
        const user = await getUser();
        if (!user) {
          console.error('failed to get user info');
          return;
        }
        setUser(user);
        console.log('user info:', user);
      } catch (error) {
        console.error('failed to get user info:', error);
      }
    };
    getUserInfo();
  }, []);
  useEffect(() => {
    // 移除重复的登录检查逻辑

    // 如果用户不存在，则不执行后续操作
    if (!user) return;

    const fetchWalletAndTransactions = async () => {
      try {
        setLoading(true);

        // 获取钱包余额
        // const { data: walletData, error: walletError } = await supabase
        //   .from('wallets')
        //   .select('balance, frozen')
        //   .eq('user_id', user.id)
        //   .single();
        const { data: walletData, error: walletError } = await get('/payment/wallet-balance');

        if (walletData && !walletError) {
          setWallet(walletData);
        } else {
          console.error('获取钱包数据失败:', walletError);
          // 如果没有钱包数据，创建一个默认的钱包对象
          setWallet({ balance: 0, frozen: 0 });
        }

        // 确定要查询的交易类型
        const typeArray = transactionType === 'recharge'
          ? ['recharge', 'activation_code', 'operation_gift', 'system_gift']
          : [transactionType];

        // 计算总交易数用于分页
        const { count, error: countError } = await supabase
          .from('billing_transactions')
          .select('*', { count: 'exact', head: true })
          .eq('user_id', user.id)
          .in('type', typeArray);

        if (countError) {
          console.error('计算交易数量失败:', countError);
        } else if (count) {
          setTotalPages(Math.ceil(count / pageSize));
        }

        // 获取分页交易记录
        const from = (currentPage - 1) * pageSize;
        const to = from + pageSize - 1;

        const { data: transactionData, error: transactionError } = await supabase
          .from('billing_transactions')
          .select('*')
          .eq('user_id', user.id)
          .in('type', typeArray)
          .order('created_at', { ascending: false })
          .range(from, to);

        if (transactionData && !transactionError) {
          setTransactions(transactionData);
        } else {
          console.error('获取交易记录失败:', transactionError);
        }
      } catch (error) {
        console.error('获取数据失败:', error);
      } finally {
        setLoading(false);
      }
    };

    fetchWalletAndTransactions();
  }, [user, currentPage, transactionType]);



  const formatDate = (dateString: string) => {
    const date = new Date(dateString);
    // 从本地存储获取语言设置
    const locale = typeof window !== 'undefined' ? localStorage.getItem('locale') || 'zh' : 'zh';
    // 映射到完整的区域设置
    const localeMap: Record<string, string> = {
      'zh': 'zh-CN',
      'en': 'en-US'
    };
    const dateLocale = localeMap[locale] || 'zh-CN';

    return new Intl.DateTimeFormat(dateLocale, {
      year: 'numeric',
      month: 'short',
      day: 'numeric',
      hour: '2-digit',
      minute: '2-digit'
    }).format(date);
  };

  const getTransactionTypeIcon = (type: string) => {
    switch (type) {
      case 'recharge':
        return <ArrowUp className="h-4 w-4" />;
      case 'final_deduct':
        return <ArrowDown className="h-4 w-4" />;
      case 'activation_code':
        return <ArrowUp className="h-4 w-4" />;
      case 'operation_gift':
        return <ArrowUp className="h-4 w-4" />;
      case 'system_gift':
        return <ArrowUp className="h-4 w-4" />;
      default:
        return null;
    }
  };

  const getTransactionTypeText = (type: string) => {
    switch (type) {
      case 'recharge':
        return t('creditPurchase');
      case 'final_deduct':
        return t('creditUsage');
      case 'activation_code':
        return t('activationCode');
      case 'operation_gift':
        return t('operationGift');
      case 'system_gift':
        return t('systemGift');
      default:
        return type;
    }
  };

  const handleTabChange = (value: string) => {
    setTransactionType(value as 'recharge' | 'final_deduct');
    setCurrentPage(1); // 切换标签时重置到第一页
  };


  return (
    <div className="min-h-screen bg-background">
      <main className="container max-w-5xl py-24 px-4 mx-auto">
        <div className="flex items-center mb-6">
          <Link href="/">
            <Button variant="ghost" size="icon" className="mr-2">
              <ChevronLeft className="h-5 w-5" />
            </Button>
          </Link>
          <h1 className="text-3xl font-bold">{t('billingAndCredits')}</h1>
        </div>

        <div className="grid grid-cols-1 md:grid-cols-3 gap-6 mb-8">
          <Card>
            <CardHeader>
              <CardTitle>{t('creditsBalance')}</CardTitle>
              <CardDescription>{t('availableCreditsDescription')}</CardDescription>
            </CardHeader>
            <CardContent>
              <div className="flex items-baseline justify-center">
                <span className="text-4xl font-bold text-purple-600">
                  {loading ? <Skeleton className="h-10 w-20" /> : wallet?.balance ?? 0}
                </span>
                <span className="ml-2 text-muted-foreground">{t('credits')}</span>
              </div>
              {(wallet?.frozen ?? 0) > 0 && (
                <div className="mt-2 text-center">
                  <span className="text-sm text-muted-foreground">
                    {wallet?.frozen} {t('creditsFrozen')}
                  </span>
                </div>
              )}
              <div className="text-center mt-2">
                <Link
                  href="https://pcnjx13aa32t.feishu.cn/wiki/Itqmw6FyViJgVoklS2wc4VUPntd"
                  target="_blank"
                  rel="noopener noreferrer"
                  className="inline-flex items-center justify-center w-full rounded-md text-xs font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 border border-input bg-background hover:bg-accent hover:text-accent-foreground h-8 px-3 py-1"
                >
                  {t('pricing')}
                </Link>
              </div>
            </CardContent>
          </Card>

          <CreditsPurchase onPurchaseComplete={() => {
            // 刷新钱包余额
            get('/payment/wallet-balance').then(({ data, error }) => {
              if (data && !error) {
                setWallet(data);
              }
            });
          }} />
        </div>

        <Card>
          <CardHeader>
            <CardTitle>{t('transactionHistory')}</CardTitle>
            <CardDescription>{t('transactionHistoryDescription')}</CardDescription>
          </CardHeader>
          <CardContent>
            <Tabs defaultValue="recharge" onValueChange={handleTabChange}>
              <TabsList className="mb-4 w-fit">
                <TabsTrigger value="recharge" className="flex gap-1">
                  <ArrowUp className="h-4 w-4" />
                  {t('purchases')}
                </TabsTrigger>
                <TabsTrigger value="final_deduct" className="flex gap-1">
                  <ArrowDown className="h-4 w-4" />
                  {t('usage')}
                </TabsTrigger>
              </TabsList>

              <TabsContent value="recharge">
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead>{t('type')}</TableHead>
                      <TableHead>{t('amount')}</TableHead>
                      <TableHead>{t('status')}</TableHead>
                      <TableHead>{t('date')}</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {loading ? (
                      Array(3).fill(0).map((_, index) => (
                        <TableRow key={index}>
                          <TableCell><Skeleton className="h-5 w-24" /></TableCell>
                          <TableCell><Skeleton className="h-5 w-16" /></TableCell>
                          <TableCell><Skeleton className="h-5 w-20" /></TableCell>
                          <TableCell><Skeleton className="h-5 w-32" /></TableCell>
                        </TableRow>
                      ))
                    ) : transactions.length === 0 ? (
                      <TableRow>
                        <TableCell colSpan={4} className="text-center py-4">
                          {t('noPurchaseTransactions')}
                        </TableCell>
                      </TableRow>
                    ) : (
                      transactions.map((transaction) => (
                        <TableRow key={transaction.id}>
                          <TableCell>
                            <div className="flex items-center gap-2">
                              {getTransactionTypeIcon(transaction.type)}
                              <span>{getTransactionTypeText(transaction.type)}</span>
                            </div>
                          </TableCell>
                          <TableCell className="text-green-600">
                            +{transaction.amount} {t('credits')}
                          </TableCell>
                          <TableCell>
                            <span className="inline-flex items-center px-2 py-1 rounded-full text-xs font-medium bg-muted text-muted-foreground">
                              {transaction.status === 'completed' ? t('confirmed') :
                                transaction.status === 'pending' ? t('pending') :
                                  t('failed')}
                            </span>
                          </TableCell>
                          <TableCell>{formatDate(transaction.created_at)}</TableCell>
                        </TableRow>
                      ))
                    )}
                  </TableBody>
                </Table>
              </TabsContent>

              <TabsContent value="final_deduct">
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead>{t('type')}</TableHead>
                      <TableHead>{t('amount')}</TableHead>
                      <TableHead>{t('status')}</TableHead>
                      <TableHead>{t('date')}</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {loading ? (
                      Array(3).fill(0).map((_, index) => (
                        <TableRow key={index}>
                          <TableCell><Skeleton className="h-5 w-24" /></TableCell>
                          <TableCell><Skeleton className="h-5 w-16" /></TableCell>
                          <TableCell><Skeleton className="h-5 w-20" /></TableCell>
                          <TableCell><Skeleton className="h-5 w-32" /></TableCell>
                        </TableRow>
                      ))
                    ) : transactions.length === 0 ? (
                      <TableRow>
                        <TableCell colSpan={4} className="text-center py-4">
                          {t('noUsageTransactions')}
                        </TableCell>
                      </TableRow>
                    ) : (
                      transactions.map((transaction) => (
                        <TableRow key={transaction.id}>
                          <TableCell>
                            <div className="flex items-center gap-2">
                              {getTransactionTypeIcon(transaction.type)}
                              <span>{getTransactionTypeText(transaction.type)}</span>
                            </div>
                          </TableCell>
                          <TableCell>
                            {transaction.amount} {t('credits')}
                          </TableCell>
                          <TableCell>
                            <span className="inline-flex items-center px-2 py-1 rounded-full text-xs font-medium bg-muted text-muted-foreground">
                              {transaction.status === 'completed' ? t('confirmed') :
                                transaction.status === 'pending' ? t('pending') :
                                  t('failed')}
                            </span>
                          </TableCell>
                          <TableCell>{formatDate(transaction.created_at)}</TableCell>
                        </TableRow>
                      ))
                    )}
                  </TableBody>
                </Table>
              </TabsContent>
            </Tabs>

            {totalPages > 1 && (
              <div className="flex items-center justify-end space-x-2 mt-4">
                <Button
                  variant="outline"
                  size="sm"
                  onClick={() => setCurrentPage(p => Math.max(1, p - 1))}
                  disabled={currentPage === 1 || loading}
                >
                  <ChevronLeft className="h-4 w-4" />
                </Button>
                <span className="text-sm">
                  {t('page')} {currentPage} / {totalPages}
                </span>
                <Button
                  variant="outline"
                  size="sm"
                  onClick={() => setCurrentPage(p => Math.min(totalPages, p + 1))}
                  disabled={currentPage === totalPages || loading}
                >
                  <ChevronRight className="h-4 w-4" />
                </Button>
              </div>
            )}
          </CardContent>
        </Card>
      </main>
    </div>
  );
}
